package com.sl.plugin.step.json;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.sl.core.engine.meta.ProcessCompDescriptorService;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.meta.row.ProcessRowDescriptor;
import lombok.Getter;
import org.noear.snack.ONode;

import java.util.Map;

/**
 *
 */
@Getter
public class JsonFilterCompDescriptor extends AbstractProcessCompDescriptor<
        JsonFilterComp, JsonFilterCompContext> implements ProcessCompDescriptorService {


    @Override
    public void loadDescriptor(Map<String, Object> map) {

    }


    @Override
    public ProcessRowDescriptor getResultDescriptor(ProcessRowDescriptor rowDescriptor) {

        String excludeJsonPath = getStrAttr("config.excludeJsonPath");
        if (StrUtil.isBlank(excludeJsonPath)) {
            return rowDescriptor;
        }

        ProcessRowDescriptor iValueMetas = jsonPathSplitBy(rowDescriptor, excludeJsonPath);

        return new ProcessRowDescriptor(iValueMetas);
    }

    private ProcessRowDescriptor jsonPathSplitBy(ProcessRowDescriptor rowDescriptor, String jsonPath) {

        //表达式替换
        String replace = StrUtil.replace(jsonPath, "\\[.*?\\]", "*");

        Object o = rowDescriptor.mockValue();

        DocumentContext parse = JsonPath.parse(o);
        parse.delete(replace);

        ProcessRowDescriptor ro = rowDescriptor.convertMetaI(parse.json());
        if (ObjectUtil.isNull(ro)) {
            return new ProcessRowDescriptor();
        }
        return ro;

    }


}
